// pages/confirmorder/confirmorder.js
var app = getApp();
var utils = require('../../utils/util.js');
Page({
  data: {
    //下单类型（0：普通订单、1、秒杀订单；2、砍价订单）
    orderPayType: 0,
    apiAddr: ['/api/v1/order/add_order', '/api/v1/index/add_spike_order', '/api/v1/bargaingoods/add_order'],
    items: [{
        name: '选择自提',
        value: '1'
      }, {
        name: '送货上门',
        value: '2'
      },
      {
        name: '产地直发',
        value: '3',
        checked: 'true'
      },
    ],
    multiArray: [
      ['今天', '明天', '后天'],
      ['08:00-10:00', '10:00-12:00', '12:00-14:00', '14:00-16:00', '16:00-18:00']
    ],
    multiIndex: [0, 0],
    valuetab: '2',
    currentTab: 0,
    currentBut: 0,
    currentBut1: 0,
    isHide: true, //支付弹窗是否显示
    coupon: 0,
    typePay: "wx_pay",
    storeId: "", //店铺id  不必须传，只是在自提的时候传输，需在最近的3家店铺获取id
    addressId: "", //地址id  不必须传 需在 我的 我的地址列表中获取id
    couponId: "", //优惠券id  不必须传 需在 、
    deliveryTime: "",
    buttonClicked: false,
    isphone: false,
    freight: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setData({
      orderPayType: options.type,
      //秒杀id
      spike_id: options.spike_id ? options.spike_id : null,
      //砍价订单id
      order_id: options.order_id ? options.order_id : null,
    });
    for (var index in that.data.multiArray[1]) {
      if (utils.time_range(that.data.multiArray[1][index])) {
        var currentTimeIndex = index;
        break;
      }
    }
    that.data.multiArray[1].splice(0, )
    that.setData({
      multiIndex: currentTimeIndex ? [0, index] : [1, 0]
    });
    wx.getStorage({
      key: 'userLocation',
      success: function(res) {
        var split = res.data.split(",");
        console.log(split);
        that.setData({
          latitude: split[0],
          longitude: split[1]
        })
      },
    })
  },
  systemlist: function(e) {
    var that = this;
    utils.http("/api/v1/common/system", {}, function(res) {
      that.setData({
        systemData: res.datas
      })
    })
  },
  getOrderList: function(callback = '') {
    var that = this;
    var orderPayType = that.data.orderPayType;
    console.log('that.data.orderPayType', orderPayType, orderPayType == 0);
    if (orderPayType == 0) {
      var listCar = wx.getStorageSync("cartInfo");
    } else if (orderPayType == 1) {
      var listCar = wx.getStorageSync("spikeGoods");
    } else if (orderPayType == 2) {
      var listCar = wx.getStorageSync("bargainGoods");
    }

    var orderCar = [];
    var goodsList = [];
    for (var i in listCar) {
      if (listCar[i].selectStatus == true) {
        orderCar.push(listCar[i])
        goodsList.push({
          goods_id: listCar[i].spec_id,
          num: listCar[i].number
        });
      }
    }
    that.setData({
      orderList: orderCar,
      goodsOrder: goodsList,
      type: wx.getStorageSync("type"),
    }, function() {
      callback();
    });
  },
  //页面展示时，加载缓存中选中的商品信息
  onShow: function() {
    var that = this;

    that.systemlist();
    that.personalInfo(function() {
      that.getOrderList(function() {
        var goodsList = that.data.goodsOrder;
        that.addressInfo();
        if (app.globalData.couponId != undefined) {
          that.setData({
            couponId: app.globalData.couponId
          })
        }
        if (app.globalData.currentGiftInfo != undefined) {
          that.setData({
            currentGiftInfo: app.globalData.currentGiftInfo
          }, function() {
            goodsList.push({
              goods_id: app.globalData.currentGiftInfo['spec_id'],
              num: 1,
              is_gift: 1
            });
            that.setData({
              goodsOrder: goodsList
            })
          })
        }
        if (app.globalData.couponMoney != undefined) {
          that.setData({
            money: app.globalData.couponMoney,
            coupon: "-" + app.globalData.couponMoney
          });
          that.get_freight(goodsList);
        } else {
          that.mycouponTap(goodsList);
          that.get_freight(goodsList);
        }
      });
    });

  },
  addressInfo: function() {
    var that = this;
    if (app.globalData.addressChid != undefined) {
      utils.http("/api/v1/address/address_info", {
        id: app.globalData.addressChid
      }, function(res) {
        app.globalData.addressChid = undefined;
        that.setData({
          defaultAddress: res.datas,
          addressId: res.datas.id
        })
      })
    } else {
      utils.http("/api/v1/address/address_info", {}, function(res) {
        console.log(res);
        if (res.datas != null) {
          that.setData({
            defaultAddress: res.datas,
            addressId: res.datas.id
          })
        }
      })
    }
  },
  //我的个人信息
  personalInfo: function(callback = "") {
    var that = this;
    utils.showLoading();
    utils.http("/api/v1/member/index", {}, function(res) {
      utils.hideLoading();
      that.setData({
        info: res.datas,
      }, function() {
        typeof callback == "function" ? callback() : ''
      })
    })
  },
  all: function(callback = '') {
    console.log('开始计算总价');
    var that = this;
    var totalPrice = 0;
    var price = 0;
    var listCar = that.data.orderList
    for (var i in listCar) {
      price = that.data.info.is_vip == 0 ? listCar[i].spec_price : listCar[i].spec_vip_price;
      var goodsPrice = (parseInt(listCar[i].number) * parseFloat(price));
      totalPrice = totalPrice + goodsPrice
    }
    var totalGoodsPrice = totalPrice;
    // 总价-积分抵扣（100：1）-优惠券金额-满减
    var coupon = app.globalData.couponMoney != undefined ? app.globalData.couponMoney : 0;

    var integral = (that.data.info.integral / 100) > 1 ? (that.data.info.integral / 100) : 0;
    //不是普通下单积分，不计算积分
    if (that.data.orderPayType != 0) integral = 0;
    totalPrice = totalPrice - integral - coupon;
    if (that.data.reduceInfo) {
      totalPrice = totalPrice - that.data.reduceInfo.reduce_price;
    }
    //判断类型
    switch (that.data.valuetab) {
      case '0':
        var totalPriceFinsh = parseFloat(totalPrice);
        break;
      case '1':
        var totalPriceFinsh = parseFloat(totalPrice) + parseFloat(that.data.systemData.store_send_price);
        break;
      case '2':
        var totalPriceFinsh = parseFloat(totalPrice) + parseFloat(that.data.freight);
        break;
    }

    that.setData({
      totalPrice: totalGoodsPrice.toFixed(2),
      oktotalPrice: totalPrice.toFixed(2),
      totalPriceFinsh: totalPriceFinsh.toFixed(2)
    }, function() {
      typeof callback == 'function' ? callback() : '';
    })
  },
  // 获取我的优惠券可使用数据 
  mycouponTap: function(goodslist) {
    var that = this;
    utils.http("/api/v1/order/my_coupon", {
      goods_list: goodslist
    }, function(res) {
      that.setData({
        coupon: "可用 (" + res.datas.use_total + "张优惠卷)"
      })
    })
  },
  //获取运费
  get_freight: function(goodslist) {
    var that = this;
    utils.http("/api/v1/order/get_freight", {
      goods_list: goodslist
    }, function(res) {
      that.setData({
        freight: res.datas
      }, function() {
        that.all(function() {
          //获取赠品个数
          that.getGiftData();
          //获取满减id，金额
          that.getReduce();
        })
      })
    })
  },
  //获取满减信息
  getReduce: function() {
    var that = this;
    if (that.data.orderPayType != 0) return;
    utils.http('/api/v1/order/get_reduce', {
      need_price: that.data.totalPrice
    }, function(res) {
      if (res.datas) {
        that.setData({
          reduceInfo: res.datas
        }, function() {
          that.all();
        });
      }
    })

  },
  //获取赠品信息
  getGiftData: function() {
    var that = this;
    if (that.data.orderPayType != 0) return;
    utils.http("/api/v1/order/gift_goods", {
      need_price: that.data.totalPrice,
    }, function(res) {
      that.setData({
        giftData: res.datas
      })
    })
  },
  //选择自提、送货上门列表
  nearbyStoreList: function(latitude, longitudeq, goodsList) {
    var that = this;
    utils.http("/api/v1/order/nearby_store", {
      latitude: latitude,
      longitude: longitudeq,
      goods_list: goodsList
    }, function(res) {
      that.setData({
        storeList: res.datas,
        storeId: res.datas[0].id
      })
    })
  },
  //订单单选项
  radioChange(e) {
    var that = this;
    this.setData({
      valuetab: e.detail.value
    }, function() {
      that.all();
    })
    that.nearbyStoreList(that.data.latitude, that.data.longitude, that.data.goodsOrder);
    if (e.detail.value == 0) {
      console.log(that.data.info.phone)
      if (that.data.info.phone == "") {
        that.setData({
          isphone: true
        })
      }
      // that.setData({
      //   addressId: "",
      // })
    }
    if (e.detail.value == 1) {
      that.setData({
        addressId: that.data.addressId,
        isphone: false
      })
    }
    if (e.detail.value == 2) {
      that.setData({
        addressId: that.data.addressId,
        isphone: false
      })
    }
  },
  //选择自提
  bindMultiPickerChange(e) {
    console.log(e);
    var that = this;
    var arr = e.detail.value;
    var one = that.data.multiArray[0][arr[0]];
    var two = that.data.multiArray[1][arr[1]];
    this.setData({
      multiIndex: e.detail.value,
      deliveryTime: one + "" + two
    })
  },

  //店铺单项选择 （送货上门）
  bindSvTap: function(e) {
    var id = e.currentTarget.dataset.current;
    this.setData({
      currentTab: id
    })
  },
  //店铺单项选择 （选择自提）
  bindButTap: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.current;
    this.setData({
      currentBut1: index,
      storeId: that.data.storeList[index].id,
    })
  },
  //优惠券
  onCouponTap: function(e) {
    var that = this;
    app.globalData.goodsList = that.data.goodsOrder;
    wx.navigateTo({
      url: '../coupon/coupon',
    })
  },
  //关闭支付弹窗
  onColseTap: function(e) {
    this.setData({
      isHide: true
    })
  },
  // getPhoneNumber  手机号授权
  getPhoneNumber: function(e) {
    var that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      // 登录
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          utils.http("/api/v1/common/get_wechat_phone", {
            js_code: res.code,
            iv: e.detail.iv,
            encryptedData: e.detail.encryptedData
          }, function(res) {
            if (res.state == 1) {
              that.phoneDiel(res.datas)
              that.setData({
                isphone: false
              })
              wx.showModal({
                title: '',
                showCancel: false,
                confirmText: "授权成功",
                content: '您已授权手机号成功',
                success: function(res) {
                  if (res.confirm) {
                    that.setData({
                      isHide: false
                    })
                  }
                }
              })
            }
          })
        }
      })
    }
  },
  phoneDiel: function(phone) {
    var that = this;
    utils.http("/api/v1/member/member_modify", {
      phone: phone
    }, function(res) {
      if (res.datas == 1) {
        this.personalInfo();
      }
    })
  },
  //打开支付弹窗
  onOrderTap: function(e) {
    var that = this;
    if (!that.data.addressId) {
      wx.showToast({
        title: '请填写地址~',
        icon: 'none'
      });
      return false;
    }
    if (that.data.valuetab == 1) {
      // 检测时间
      var myDate = new Date();
      var nowH = myDate.getHours();
      var multiIndex = that.data.multiIndex; //获取当前小时数(0-23)
      if (nowH >= 10 && multiIndex[0] == 0 && multiIndex[1] == 0) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }
      if (nowH >= 12 && multiIndex[0] == 0 && multiIndex[1] <= 1) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }
      if (nowH >= 14 && multiIndex[0] == 0 && multiIndex[1] <= 2) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }
      if (nowH >= 16 && multiIndex[0] == 0 && multiIndex[1] <= 3) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }
      if (nowH >= 18 && multiIndex[0] == 0 && multiIndex[1] <= 4) {
        wx.showToast({
          title: '请重新选择正确的配送时间',
          icon: "none"
        })
        return false;
      }
    }
    this.setData({
      isHide: false
    })
  },
  //支付方式
  paymentTypeTap: function(e) {
    var id = e.currentTarget.dataset.id;
    var currentBut = id;
    this.setData({
      currentBut: currentBut,
      typePay: e.currentTarget.dataset.type,
      buttonClicked: false
    })
  },
  //商品支付完成清空对应商品
  shoppClear: function(e) {
    var that = this;
    var cartInfo = wx.getStorageSync("cartInfo");
    var number = wx.getStorageSync("number");
    var inn = 0;
    for (var i in cartInfo) {
      for (var j in that.data.goodsOrder) {
        if (cartInfo[i].spec_id == that.data.goodsOrder[j].goods_id) {
          console.log(cartInfo[i])
          inn = inn + cartInfo[i].number
          cartInfo.splice(i, 1)
        }
      }
    }
    console.log('支付完成后的购物车中的数量', parseInt(number - inn))
    wx.setStorageSync("number", parseInt(number - inn))
    wx.setStorageSync("cartInfo", cartInfo)
  },
  //立即支付
  onOrderSuccessTap: function(e) {
     
    var that = this;
      console.log(that.data.info.id, "liuliu")
    if (that.data.buttonClicked == false) {
      utils.showLoading();
      that.setData({
        buttonClicked: true
      })

      var param = that.getOrderPayParam();
      utils.http(that.data.apiAddr[that.data.orderPayType], param, function(res) {
        utils.hideLoading();
        if (res.state == 1) {
          if (that.data.typePay == "wx_pay") {
            wx.requestPayment({
              timeStamp: res.datas.timeStamp,
              nonceStr: res.datas.nonceStr,
              package: res.datas.package,
              signType: res.datas.signType,
              paySign: res.datas.paySign,
                inv_id: that.data.info.id,
              success() {
                that.paySuccessCallback(res);
              },
              fail(res) {
                that.setData({
                  buttonClicked: false
                })
              }
            })
          } else {
            that.paySuccessCallback(res);
          }
        } else if (res.state == 10001) {
          that.paySuccessCallback(res)
        } else {
          utils.message(res.datas);
          that.setData({
            buttonClicked: false
          })
        }
      })
    }
  },
  getOrderPayParam: function() {
    var that = this;
    var param = {
      reduce_id: that.data.reduceInfo ? that.data.reduceInfo.id : 0,
      goods_list: that.data.goodsOrder,
      payment_code: that.data.typePay,
      get_type: that.data.valuetab,
      store_id: that.data.storeId,
      address_id: that.data.addressId,
      coupon_id: that.data.couponId,
      delivery_time: that.data.deliveryTime,
      inv_id: that.data.info.id
    };
    if (that.data.orderPayType == 1) {
      param.spike_id = that.data.spike_id
    } else if (that.data.orderPayType == 2) {
      param.order_id = that.data.order_id;
    }
    return param;
  },
  paySuccessCallback: function(res) {
    var that = this;
    that.shoppClear();
    app.globalData.couponMoney = undefined;
    app.globalData.couponId = undefined;
    app.globalData.currentGiftInfo = undefined;
    wx.redirectTo({
      url: '../ordersuccess/ordersuccess?orderid=' + res.datas.order_id + "&totalprice=" + res.datas.total_price+"&orderType=1"
    })
  },
  //跳入我的地址页面
  onMyAddressTap: function(e) {
    app.globalData.typeaddress = 0
    wx.navigateTo({
      url: '../personal/myaddress/myaddress?typeaddress=' + app.globalData.typeaddress,
    })
  },
  //跳转到选择赠品页面
  giftLists: function() {
    var that = this;
    wx.navigateTo({
      url: '/pages/giftLists/giftLists?need_price=' + that.data.totalPrice,
    })
  }
})